import { http } from '@/api/eggread/baseRequest'
import eggBasicContainer from "@/components/egg-read/common/basicContainer.vue"
export default (app, option = {}) => {
  let mixins = {
    data() {
      return {
        // 更新时会填充的数据
        form: {},
        // 分页数据
        page: {
          total: 0,
          pageSize: 10,
          pageSizes: [5, 10, 20,100]
        },
        // api 请求路径
        api: {
          page: "",
          save: "",
          update: "",
          delete: ""
        },
        // 搜索请求参数
        params: {},
        // 所有的全选对象
        checks: [],
        // 图片上传是否为数组 默认 false 
        imageIsArray: false,
        baseParam: {},
        title: "运营后台导出数据"
      }
    },
    computed: {
      option() {
        return require(`@/option/${option.name}`).default(this)
      },
      bindVal() {
        return {
          ref: 'crud',
          option: this.option,
          data: this.data,
          tableLoading: this.loading
        }
      },
      onEvent() {
        return {
          'on-load': this.getList,
          'row-save': this.rowSave,
          'row-update': this.rowUpdate,
          'row-del': this.rowDel,
          'refresh-change': this.refreshChange,
          'search-reset': this.searchChange,
          'search-change': this.searchChange
        }
      },
      rowKey() {
        return option.rowKey || 'id'
      }
    },
    methods,
    components
  }
  app.mixins = app.mixins || [];
  app.mixins.push(mixins)
  return app;
}

let methods = {
  /**获取列表 */
  async getList() {
    let flag = this.beforeGetList()
    if (!flag) {
      return
    }
    this.loading = true;
    //清空表格列表
    this.data = [];
    //发送请求获取数据
    let response = await http(
      this.api.page,
      { ...this.params, ...this.baseParam },
      this.page
    );
    if (response != null) {
      this.page = response.page;
      this.data = response.data;
    }
    this.loading = false;
    this.afterGetList()
  },
  /**保存 */
  async rowSave(row, done, loading) {
    let flag = this.beforeRowSave(row, done)
    if (!flag) {
      loading()
      return
    }
    delete row["id"];
    let data = await http(this.api.save, row);
    if (!data) {
      loading();
      return;
    }
    this.getList();
    done && done();
    this.afterRowSave(row, done)
  },
  /**修改 */
  async rowUpdate(row, index, done, loading) {
    let flag = this.beforeRowUpdate(row, index, done, loading)
    if (!flag) {
      return
    }
    let data = await http(this.api.update, row);
    if (!data && loading) {
      loading();
      return;
    }
    this.getList();
    done && done()
    this.afterRowUpdate(row, index, done, loading)
  },
  /**刷新 */
  refreshChange() {
    let flag = this.beforeRefreshChange()
    if (!flag) {
      return
    }
    this.getList();
    this.$message.success("刷新成功");
    this.afterRefreshChange()
  },
  /**删除 */
  rowDel(row) {
    let flag = this.beforeRowDel(row)
    if (!flag) {
      return
    }
    this.$confirm("此操作将永久删除, 是否继续?", "提示", {
      type: "warning",
    })
      .then(async () => {
        let data = await http(
          this.api.delete,
          row
        );
        if (!data) {
          return;
        }
      })
      .then(() => {
        this.$message.success("删除成功");
        this.getList();
      });
    this.afterRowDel(row)
  },
  /**搜索 */
  searchChange(param, done) {
    let flag = this.beforeSearchChange(param, done)
    if (!flag) {
      return
    }
    // 获取搜索条件
    this.params = param
    console.log(this.params)
    // 判断是否存在开始时间和结束时间
    if (this.params.dateSelect) {
      let dateSelect = this.params.dateSelect
      let startTime = dateSelect[0]
      let endTime = dateSelect[1]
      delete this.params['dateSelect']
      this.params['startTime'] = startTime.getTime()
      this.params['endTime'] = endTime.getTime()
    }
    // 当前页数为1
    this.page.currentPage = 1;
    this.getList();
    if (done) done();
    this.afterSearchChange(this.params, done)
  },
  /** 导出数据 */
  async downExcel() {
    this.$message.info("请耐心等待导出完毕(0分钟-5分钟)")
    let response = await http(
      this.api.page,
      { ...this.params, ...this.baseParam },
      // 固定只能转换 25000 条数据
      {
        pageSize: 25000
      }
    );
    let columnList = [...this.option.column]
    console.log(this.$refs.crud)
    let dic = this.$refs.crud.DIC
    let dicParam = this.setDic(dic, columnList)
    let data = response.data
    if (!data) {
      return
    }
    data.forEach(item => {
      // 循环需要进行替换的数据对象
      Object.keys(dicParam).forEach(value => {
        let type = dicParam[value]['type'];
        if (type == 'dic') {
          item[value] = dicParam[value][item[value]]
        } else if (type == 'date') {
          item[value] = this.formatFullTime(item[value])
        } else if (type == 'hide') {
          delete item[value]
        }

      })
    })
    this.$export.excel({
      title: this.title,
      columns: this.option.column,
      data: data
    })
  },
  /**勾选所有 */
  selectionChange(row) {
    this.checks = row
  },
  beforeGetList() {
    return true
  },
  afterGetList() {

  },
  beforeRowSave(row, done) { return true },
  afterRowSave(row, done) { },
  beforeRowUpdate(row, index, done, loading) { return true },
  afterRowUpdate(row, index, done, loading) { },
  beforeRefreshChange() { return true },
  afterRefreshChange() { },
  beforeRowDel(row) { return true },
  afterRowDel(row) { },
  beforeSearchChange(params, done) { return true },
  afterSearchChange(params, done) { },
  beforeSelectionChange(row) { return true },
  afterSelectionChange(row) { },
  setDic(dic, column) {
    let dicParam = {};
    column.forEach(item => {
      // 处理字典类型
      let prop = item.prop
      if (dic[prop]) {
        let dicList = dic[item.prop]
        let dicParamNode = {}
        let propLabel = item.props.label
        let propValue = item.props.value
        dicList.forEach(value => {
          dicParamNode[value[propValue]] = value[propLabel]
        })
        dicParamNode.type = 'dic'
        dicParam[prop] = dicParamNode

      }
      // 处理日期类型
      if (item.type == 'datetime') {
        dicParam[prop] = {}
        dicParam[prop]['type'] = 'date'
      }
      // 处理隐藏对象
      if (item.hide) {
        dicParam[prop] = {}
        dicParam[prop]['type'] = 'hide'
      }
    })
    return dicParam;
  },
  formatFullTime(timestamp, format = 'YYYY-MM-DD hh:mm:ss') {
    var date = new Date(timestamp);
    var Y = date.getFullYear();
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate());
    var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours());
    var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());
    var s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
    return format.replace('YYYY', Y).replace('MM', M).replace('DD', D).replace('hh', h).replace('mm', m).replace('ss', s)
  }
}

let components = {
  "egg-basic-container": eggBasicContainer
}